package com.d3works.apps.base.web;

import com.d3works.apps.base.db.AppBase;
import com.d3works.apps.base.db.ModelEmailLink;
import com.d3works.apps.base.exceptions.BaseExceptionMessage;
import com.d3works.apps.base.service.ModelEmailLinkService;
import com.d3works.common.ObjectUtils;
import com.d3works.db.EntityHelper;
import com.d3works.exception.D3worksException;
import com.d3works.exception.db.repo.TraceBackRepository;
import com.d3works.i18n.I18n;
import com.d3works.inject.Beans;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;

public class ModelEmailLinkController {

  public void validateModelFields(ActionRequest request, ActionResponse response)
      throws D3worksException {

    AppBase appBase = request.getContext().asType(AppBase.class);
    if (ObjectUtils.isEmpty(appBase.getEmailLinkList())) {
      return;
    }

    for (ModelEmailLink modelEmailLink : appBase.getEmailLinkList()) {
      modelEmailLink = EntityHelper.getEntity(modelEmailLink);
      if (!Beans.get(ModelEmailLinkService.class).validateModelFields(modelEmailLink)) {
        throw new D3worksException(
            TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
            String.format(
                I18n.get(BaseExceptionMessage.INVALID_FIELD),
                modelEmailLink.getEmailField(),
                modelEmailLink.getMetaModel().getName()));
      }
    }
  }
}
